//
//  UserLoginViewController.m
//  DSYDouban
//
//  Created by dllo on 16/1/1.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "UserLoginViewController.h"
#import "LabelTextView.h"
#import "UserRegisterViewController.h"
#import "DBManager.h"

#define lWidth  self.view.frame.size.width
#define lHeight self.view.frame.size.height;

@interface UserLoginViewController ()

@property (nonatomic, retain) LabelTextView *userLTView;

@property (nonatomic, retain) LabelTextView *passLTView;

@end

@implementation UserLoginViewController

- (void)dealloc
{
    [_userLTView release];
    [_passLTView release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"用户登陆";
    
    self.userLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 30, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_userLTView];
    _userLTView.LTLabel.text = @"用户名: ";
    _userLTView.LTTextField.placeholder = @"请输入用户名";
    _userLTView.LTTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [_userLTView release];
    
    self.passLTView = [[LabelTextView alloc] initWithFrame:CGRectMake(15, 75, self.view.frame.size.width - 60, 35)];
    [self.view addSubview:_passLTView];
    _passLTView.LTLabel.text = @"密    码: ";
    _passLTView.LTTextField.placeholder = @"请输入密码";
    _passLTView.LTTextField.secureTextEntry = YES;
    _passLTView.LTTextField.clearsOnBeginEditing = YES;
    [_passLTView release];
    
    
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake(lWidth / 5, 150, lWidth / 5, 35);
    loginButton.backgroundColor = [UIColor colorWithRed:0.1 green:0.5 blue:0.1 alpha:1];
    [loginButton setTitle:@"登 陆" forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginButton.layer.cornerRadius = 5.0;
    loginButton.showsTouchWhenHighlighted = YES;
    [self.view addSubview:loginButton];
//    [loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *registerButotn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButotn.frame = CGRectMake(lWidth * 3 / 5 , loginButton.frame.origin.y, lWidth / 5, 35);
    registerButotn.backgroundColor = [UIColor colorWithRed:0.5 green:0.1 blue:0.1 alpha:1];
    [registerButotn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerButotn setTitle:@"注 册" forState:UIControlStateNormal];
    registerButotn.layer.cornerRadius = 5.0;
    registerButotn.showsTouchWhenHighlighted = YES;
    [self.view addSubview:registerButotn];
    
    [registerButotn addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    
}


- (void)loginAction: (UIButton *)button {
    
    BOOL isUser = ([_userLTView.LTTextField.text isEqualToString:@"dsy"]);
    BOOL isPass = [_passLTView.LTTextField.text isEqualToString:@"dsy1672"];
    
    NSLog(@"%@", _userLTView.LTTextField.text);
    
    NSLog(@"%d ------ %d", isUser, isPass);
    
    if (isUser && isPass) {  // 密码和用户名是正确地
        
            
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"成功登陆" preferredStyle:UIAlertControllerStyleAlert];
    
        [self presentViewController:alert animated:YES completion:^{
            NSLog(@"%@  -  %@", _userLTView.LTTextField.text, _passLTView.LTTextField.text);
            
            [alert dismissViewControllerAnimated:YES completion:^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
        }];
        
        
//        [self.navigationController popViewControllerAnimated:YES];
        
    } else if (isUser && !isPass) {  // 密码不正确
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"密码错误" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_passLTView.LTTextField becomeFirstResponder];
            [_passLTView.LTTextField becomeFirstResponder];
            
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:OKAction];
        [alert addAction:CancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {  // 用户名不正确的时候
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"用户名错误" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [_userLTView.LTTextField becomeFirstResponder];
        }];
        UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:OKAction];
        [alert addAction:CancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];

        
    }
    
}

- (void)login {
    
    if ([self isSuccessLogin]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"成功登陆" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
            [alert dismissViewControllerAnimated:YES completion:^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
        }];
        
        [self setStatus:1 withUserName:_userLTView.LTTextField.text];
        
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误提示" message:@"您的账号或密码有误" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            [NSThread sleepForTimeInterval:2];
            [alert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
    }
}

// 对账户登陆状态设置
- (void)setStatus:(NSInteger)status withUserName:(NSString *)username {
    
    [[DBManager createDB] update:[NSString stringWithFormat:@"update userInfo set status = %ld where username = '%@'", status, username]];
}


// 从数据库中查找用户并检验输入的正确性
- (BOOL)isSuccessLogin {
    
    // 从数据库中查询用户
    NSString *sql = [NSString stringWithFormat:@"select * from userInfo where username = '%@'", _userLTView.LTTextField.text];
    NSArray *arr = [[DBManager createDB] select:sql];
    
    NSLog(@"---------%ld--------", arr.count);
    
    // 由于数据库用户名的唯一性，每次查询得到的结果只有一个
    if (arr == nil || arr.count == 0) {  // 如果arr为空，就不用判断arr.count了
        return NO;
    } else {
        NSDictionary *dic = [arr firstObject];  // 如果查询到用户
        
        // 判断用户密码的正确性
        if ([[dic objectForKey:@"password"] isEqualToString:_passLTView.LTTextField.text]) {
            return YES;
        } else {
            return NO;
        }

    }
    
    
    return NO;
}



// 回收键盘
- (void)registerAction: (UIButton *)button {
    
    UserRegisterViewController *regVC = [[UserRegisterViewController alloc] init];
    
    regVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:regVC animated:YES];
    
    
//    [self presentViewController:regVC animated:YES completion:^{
//        
//    }];
    
    [regVC release];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
